import { createRouter, createWebHashHistory } from "vue-router";
import { isLogined } from "../utils/auth";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: () => import("../components/home.vue"),
    },
    {
      path: "/list",
      name: "list",
      component: () => import("../components/list.vue"),
    },
    {
      path: "/cart",
      name: "cart",
      component: () => import("../components/cart.vue"),
      meta: {
        needLogin: true,
      },
    },
    {
      path: "/user",
      name: "user",
      component: () => import("../components/user.vue"),
      meta: {
        needLogin: true,
      },
    },
    {
      path: "/user-info",
      name: "userInfo",
      component: () => import("../components/user-info.vue"),
      meta: {
        needLogin: true,
      },
    },
    {
      path: "/change-pwd",
      name: "changePwd",
      component: () => import("../components/change-pwd.vue"),
      meta: {
        needLogin: true,
      },
    },
    {
      path: "/order",
      name: "order",
      component: () => import("../components/Order.vue"),
    },
    {
      path: "/my-order",
      name: "MyOrder",
      component: () => import("../components/My-order.vue"),
      meta: {
        needHideTabBar: true, //是否需要隐藏底部导航
      },
    },
    {
      path: "/detail",
      name: "detail",
      component: () => import("../components/Detail.vue"),
      meta: {
        needHideTabBar: true, //是否需要隐藏底部导航
      },
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../components/Login.vue"),
      meta: {
        needHideTabBar: true, //是否需要隐藏底部导航
      },
    },
    {
      path: "/reg",
      name: "reg",
      component: () => import("../components/Reg.vue"),
      meta: {
        needHideTabBar: true, //是否需要隐藏底部导航
      },
    },
  ],
});

// 全局守卫，跳转之前执行
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    //如果跳转的页面需要登录，判断是否登录
    if (isLogined()) {
      //如果已经登录，直接下一步
      next();
    } else {
      next({
        name: "login",
      });
    }
  } else {
    next();
  }
});

export default router;
